package org.theSeed.base.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator;
import lombok.SneakyThrows;

/**
 * yaml工具
 */
public class YmlUtil {
    private static ObjectMapper yamlMapper;

    static {
        //null值忽略
        YAMLFactory yamlFactory = new YAMLFactory();
        yamlFactory.enable(YAMLGenerator.Feature.MINIMIZE_QUOTES);
        yamlFactory.disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER);

        yamlMapper = new ObjectMapper(yamlFactory);
        yamlMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }

    /**
     * 对象转yaml
     * @param obj
     * @return
     */
    @SneakyThrows
    public static String toYaml(Object obj) {
        return yamlMapper.writeValueAsString(obj);
    }

    /**
     * yaml转对象
     * @param yaml
     * @param type
     * @return
     * @param <T>
     * @throws Exception
     */
    public static <T> T fromYaml(String yaml, Class<T> type) throws Exception {
        return yamlMapper.readValue(yaml, type);
    }
}
